//
//  JRADLaunchManager.swift
//  JRADLaunchModule
//
//  Created by 京睿 on 2017/5/22.
//  Copyright © 2017年 JingRuiWangKe. All rights reserved.
//

import UIKit
import JRTimer
import SDWebImage

public class JRADLaunchManager: ADLaunchable {
    
    public weak var configDelegate: ADLaunchableConfigDelegate!
    
    fileprivate typealias this = JRADLaunchManager
    
    //    fileprivate static var tmp: UIViewController!
    
    private init() { }
    
//    fileprivate static var window: UIWindow! = {
//        guard let foo = UIApplication.shared.keyWindow else { return nil }
//        return foo
//    } ()
    
    public static var manager: JRADLaunchManager = {
        let foo = this()
        return foo
    } ()
}

extension JRADLaunchManager {
    public func set() {
        exist()
    }
    
    private func startShow() {
        let launch = JRADViewController.init(by: configDelegate?.launch(countdownFor: self))
        configDelegate?.launch(canShow: self, launch: launch)
    }
    
    public func jump() {
        configDelegate.launch(didSelect: self)
    }
    
    public func exit() {
        //        this.window.rootViewController = this.tmp
        configDelegate.launch(exit: self)
    }
    
    /// 广告图本地缓存url
    public var cacheUrl: String? {
        return UserDefaults.standard.object(forKey: loadingKey) as? String
    }
    
    public var isExist: Bool {
        guard let url = cacheUrl else { return false }
        return SDWebImageManager.shared().diskImageExists(for: URL.init(string: url))
    }
    
    fileprivate func exist() {
        guard let str = configDelegate?.launch(imageUrlFor: self) else { return }
        if let url = cacheUrl {
            if url == str {
                if isExist {
                    startShow()
                } else {
                    download(url)
                }
            } else {
                startShow()
                download(str)
            }
        } else {
            download(str)
        }
    }
    
    public func download(_ str: String) {
        if let local = cacheUrl, local == str { return }
        guard let url = URL.init(string: str) else { return }
        SDWebImageDownloader.shared().downloadImage(with: url, options: SDWebImageDownloaderOptions.init(rawValue: 0), progress: nil) {
            UserDefaults.standard.setValue(str, forKey: loadingKey)
            SDImageCache.shared().store($0.0, forKey: str, toDisk: true)
        }
    }
}
